package com.net.xpay.core.helper;

import com.net.xpay.common.domain.User;
import com.net.xpay.common.domain.UserShard;
import com.net.xpay.common.enums.user.AppVersion;
import com.net.xpay.common.manager.UserShardManager;
import com.net.shard.manager.ShardSettingManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 2020/4/28 14:25

 * 分片算法
 */
@Component
public class ShardHelper {

    @Autowired
    private ShardSettingManager shardSettingManager;

    @Autowired
    private UserShardManager userShardManager;

    public Long getShardId(User user) {
        //渠道商家用户需要和渠道主一个库方便渠道主查询数据
        if (AppVersion.CHANNEL_SLAVE.equals(user.getAppVersion())) {
            UserShard channelMasterUserShard = userShardManager.getById(user.getChannelMasterUserId());
            return channelMasterUserShard.getShardId();
        }

        long shardCount = shardSettingManager.getShardCount("xpay");
        return user.getId() % shardCount;
    }
}
